import { useState, useEffect, useMemo, useRef } from "react";
import { Button, Spin, Select, Radio, Image, Dropdown, Space, Menu, Popover, message } from 'antd';
import cls from 'classnames';
import IconFont from '@/components/IconFont';
import { formatZjfImg } from '@/utils/utils.jsx';
import { throttle, find, over } from 'lodash';
import { DownOutlined, UpOutlined, SwapOutlined } from '@ant-design/icons';
import { getFashionGoodsOp, getHotGoodsSpecOp } from '../../../services';
import styles from './index.module.less';

const { Option } = Select;

const overlayStyle = {
  maxHeight:'500px',
  overflowY:'auto',
  overflowX: 'hidden'
}

export const CustomRadioBtn = ({ isSelect, children, onClick, style = {}, hasPosition }) => {

  return (<ul className={`${styles.radioBtnWrapper} ${isSelect ? styles.isSelect : ''}`} onClick={onClick} style={{...style, paddingLeft: 0, marginBottom: 0}}>
    {children}
    { hasPosition && <div style={{position:'absolute', right:'0px', bottom: '-8px'}}>
        <IconFont type="icona-juxing11766" />
      </div>}
  </ul>)
}

const CustomMenu1 = ({ open, initText = '', field, dataSource = [], onOpenChange, isOnlyContain, changeRadio }) => {

  const [choose, setChoose] = useState([]);

  const showText = useMemo(()=> {
    return choose?.length ? `已选${choose?.length}` : initText;
  }, [choose])

  useEffect(()=>{
    if(choose?.length){
      setChoose(choose.filter(item=>Boolean(find(dataSource, [field, item]))));
    }
  }, [dataSource])

  const handleChoose = (val) => {
    if(choose.includes(val)){
      setChoose(choose.filter(item=>item != val));
    }else{
      setChoose([...choose, val]);
    }
  }

  const renderMenu = () => {
    const menuItems = dataSource.map((item, index)=>{
      const { sysSkuCode, sysSpuId, sysGoodsImage, storeId, sysGoodsName, sysGoodsSpec, goodsNum, orderNum } = item;

      return ({
        key: index + 1,
        label: <div className={`${styles.fashionItem} ${choose.includes(item[field]) ? styles.isActive : ''}`} key={sysSkuCode || sysSpuId} onClick={()=>handleChoose(item[field])}>
        <div style={{display:'flex', justifyContent:'space-between', padding: '4px 8px'}}>
          <div className={styles.imageBox}>
            <Image width={64} height={64} src={formatZjfImg(sysGoodsImage, storeId)} fallback="" />
            <span>{index + 1}</span>
          </div>
          <div className={styles.goodsInfo}>
            <p className='textOverflowMultiThree'>{sysGoodsName}</p>
          </div>
          <div className={styles.orderNumBox}>{orderNum}单</div>
          <div className={styles.goodsNumBox}>{goodsNum}件</div>
        </div>
        {choose.includes(item[field]) && <div className={styles.positionIcon}><IconFont type="iconsub-select" /></div>}
      </div>
      })
    })
    menuItems.unshift({
      key: 'radio',
      label: <div className={styles.isOnlyContainBox}>
      筛选商品订单：
      <Radio.Group value={isOnlyContain} onChange={changeRadio}>
        <Radio value={true}>仅包含</Radio>
        <Radio value={false}>包含</Radio>
      </Radio.Group>
    </div>
    })
    return <Menu items={menuItems} />
  }

  return (<>
  <Dropdown open={open} overlay={renderMenu()} onOpenChange={(e)=>onOpenChange(e, field == 'sysSpuId' ? 2 : 1, choose)} trigger={['click']} overlayClassName={styles.customDropdown} overlayStyle={overlayStyle}>
      {/* <span onClick={()=>handleClick(item[field])}> */}
      <Space style={{cursor:'pointer'}}>
        {showText}
        {/* <span className={`${open ? styles.rotate : ''}`}><DownOutlined /></span> */}
        {open ? <UpOutlined /> : <DownOutlined />}
        {/* <DownOutlined /> */}
      </Space>
    {/* </span> */}
  </Dropdown>
  </>)
}

const CustomMenu2 = ({ open, initText = '', field, spuSelected, dataSource = [], onOpenChange, handleTriggerSearch, isOnlyContain,  changeRadio }) => {

  const [choose, setChoose] = useState([]);

  const showText = useMemo(()=> {
    return choose?.length ? `已选${choose?.length}` : initText;
  }, [choose])

  useEffect(()=>{
    let newChoose = [];
    if(choose?.length){
      newChoose = choose.filter(item=>Boolean(find(dataSource, [field, item])));
      setChoose(newChoose);
    }
    if(dataSource?.length){
      timer = setTimeout(()=>handleTriggerSearch(newChoose?.length ? newChoose : dataSource.map(item=>item.sysSkuCode)), 1000);
    }
  }, [dataSource])

  const handleChoose = (val) => {
    if(choose.includes(val)){
      setChoose(choose.filter(item=>item != val));
    }else{
      setChoose([...choose, val]);
    }
  }

  const renderMenu = () => {
    const menuItems = dataSource.map((item, index)=>{
      const { sysSkuCode, sysSpuId, sysGoodsSpec } = item;

      return ({
        key: index + 1,
        label: <div className={`${choose.includes(item[field]) ? styles.isActive : ''}`} key={sysSkuCode || sysSpuId} onClick={()=>handleChoose(item[field])} style={{maxWidth: '420px', height: '30px', display:'flex', alignItems:'center', wordBreak: 'break-all'}}>
        <Popover content={<div style={{maxWidth: '420px'}}>{sysGoodsSpec} {sysSkuCode}</div>} zIndex={10000} mouseEnterDelay={0.8}>
          <p className='textOverflowMultiOne' style={{padding:"0 12px"}}>{sysGoodsSpec} {sysSkuCode}</p>
        </Popover>
        {choose.includes(item[field]) && <div className={styles.positionIcon}><IconFont type="iconsub-select" /></div>}
      </div>
      })
    })
    menuItems.unshift({
      key: 'radio',
      label: <div className={styles.isOnlyContainBox}>
      筛选商品订单：
      <Radio.Group value={isOnlyContain} onChange={changeRadio}>
        <Radio value={true}>仅包含</Radio>
        <Radio value={false}>包含</Radio>
      </Radio.Group>
    </div>
    })
    return <Menu items={menuItems} />
  }

  const handleOpenChange = (bool) =>{
    if(bool && !spuSelected?.length){
      return message.info('请先选择商品');
    }
    onOpenChange(bool, choose?.length ? choose : dataSource.map(item=>item.sysSkuCode));
  }

  return (<>
  <Dropdown open={open} overlay={renderMenu()} onOpenChange={handleOpenChange} trigger={['click']} overlayClassName={styles.customDropdown} overlayStyle={overlayStyle}>
      {/* <span onClick={()=>handleClick(item[field])}> */}
      <Space style={{cursor:'pointer'}}>
        {showText}
        {/* <span className={`${open ? styles.rotate : ''}`}><DownOutlined /></span> */}
        {open ? <UpOutlined /> : <DownOutlined />}
        {/* <DownOutlined /> */}
      </Space>
    {/* </span> */}
  </Dropdown>
  </>)
}

let timer;
export default ({ hotGoodsCount, searchForm, handleOk }) => {

  const [showStatus, setShowStatus] = useState(0);

  const [fetching, setFetching] = useState(false);
  const [fashionData, setFashionData] = useState([]);//爆款商品
  const [specData, setSpecData] = useState([]);//颜色规格

  const [hasSelectedGoods, setHas] = useState(false);

  const stageParams = useRef({
    spuSelected: [],//按款搜索 所选款式
  })

  useEffect(() => {
  }, [])

  //获取爆款商品排行
  const handleGetFashion = async (e) => {
    setFetching(true);
    const { data, success } = await getFashionGoodsOp({ showStatus, isOnlyContain: e ? e.target.value : isOnlyContain });
    setFetching(false);
    if(success){
      setFashionData(data || []);
    }
  }

  //获取颜色规格
  const getHotGoodsSpec = async (selected) => {
    if(!selected?.length) {
      searchForm?.sysSkuCodeArr?.length && handleOk(isOnlyContain, []);
      return setSpecData([]);
    };
    const { data, success} = await getHotGoodsSpecOp(selected);
    if(success && data?.length){
      setSpecData(data);
    }
  }

  const [selected, setSelected] = useState([]);
  const [selected2, setSelected2] = useState([]);
  const [visible, setVisible] = useState(false);
  const [isOnlyContain, setRadioType] = useState(true);

  useEffect(() => {
    selected?.length && setSelected([]);
    selected2?.length && setSelected2([]);
    fashionData?.length && setFashionData([]);
    visible && setVisible(false);
    !isOnlyContain && setRadioType(true);
  }, [showStatus])

  useEffect(()=>{
    if(showStatus == 0 && selected?.length){
      handleOk(isOnlyContain, selected);
    }
  }, [selected])

  useEffect(()=>{
    if(showStatus == 0){
      if(selected?.length){
        handleOk(isOnlyContain, selected);
      }
    }else if(selected2?.length){
      handleOk(isOnlyContain, selected2);
    }else{
      // getHotGoodsSpec();
    }
  }, [isOnlyContain])

  const value1 = useMemo(()=>{
    if(selected?.length){
      if(showStatus == 0){
        return `已选商品编码${selected[0]}`;
      }else{
        return `已选${selected?.length}`;
      }
    }
   return `您有${hotGoodsCount || 0}件爆款商品待打印`;
  }, [hotGoodsCount, selected])

  const newRenderGoods = () => {
    return (<>
      {
        fashionData.map((item, index) => {
          const { sysSkuCode, sysSpuId, sysGoodsImage, storeId, sysGoodsName, sysGoodsSpec, goodsNum, orderNum } = item;

          return (<Option value={sysSkuCode || sysSpuId} key={sysSkuCode || sysSpuId}>
            <div className={styles.fashionItem} key={sysSkuCode || sysSpuId}>
              <div className={styles.imageBox}>
                <Image width={64} height={64} src={formatZjfImg(sysGoodsImage, storeId)} fallback="" />
                <span>{index + 1}</span>
              </div>
              <div className={styles.goodsInfo}>
                <p className='textOverflowMultiOne'>{sysSkuCode}</p>
                <p className='textOverflowMultiOne'>{sysGoodsName}</p>
                <p className='textOverflowMultiOne'>{sysGoodsSpec}</p>
              </div>
              <div className={styles.orderNumBox}>{orderNum}单</div>
              <div className={styles.goodsNumBox}>{goodsNum}件</div>
            </div>
          </Option>)
        })
      }
    </>)
  }

  const radioContent = () => {
    return (<div className={styles.isOnlyContainBox}>
      筛选商品订单：
      <Radio.Group 
        value={isOnlyContain} 
        onChange={(e) => {
          setRadioType(e.target.value);
          handleGetFashion(e);
        }}
      >
        <Radio value={true}>仅包含</Radio>
        <Radio value={false}>包含</Radio>
      </Radio.Group>
    </div>)
  }

  //第一个下拉
  const menuProps1 = {
    isOnlyContain,
    open: visible == 2,
    initText: '选择商品',
    field: 'sysSpuId',
    dataSource: fashionData,
    onOpenChange(bool, val, selected){
      console.log(selected)
      if(bool){
        handleGetFashion();
        setVisible(val);
      }else if(showStatus == 1){
        setHas(selected?.length);
        stageParams.current.spuSelected = selected;
        getHotGoodsSpec(selected);
        setVisible(false);
      }
    },
    changeRadio(e){
      console.log(e.target.value)
      setRadioType(e.target.value);
    }
  }

 //规格下拉
  const menuProps2 = {
    isOnlyContain,
    open: visible == 3,
    initText: '颜色规格',
    field: 'sysSkuCode',
    dataSource: specData,
    spuSelected: stageParams.current.spuSelected,
    onOpenChange(bool, list){
      if(timer){
        clearTimeout(timer);
        timer = null;
      }
      if(bool){
        setVisible(3);
      }else{
        setVisible(false);
        handleOk(isOnlyContain, list);
      }
    },
    handleTriggerSearch(list){
      handleOk(isOnlyContain, list);
    },
    changeRadio(e){
      setRadioType(e.target.value);
    }
  }

  const handleCheck = () => {
    selected?.length && setSelected([]);
    hasSelectedGoods && setHas(false);
    if(selected?.length || hasSelectedGoods){
      handleOk(isOnlyContain, []);
    }
  }

  return (<div><CustomRadioBtn>
    <li className={cls(styles.firstLabel, (selected?.length || hasSelectedGoods) ? styles.isSelect : '')} onClick={e=>e.stopPropagation()}>
      {/* <div className={styles.isSelect} style={{display:'flex'}}> */}
       <div onClick={handleCheck}><span style={{color:'red'}}>爆款商品-</span><span style={{color:"#333333"}}>按{showStatus ? '款' : '商品'}</span></div>
       <SwapOutlined onClick={()=>{setShowStatus(showStatus ? 0 : 1);handleCheck()}} />
       {/* </div> */}
    </li>
    {
      showStatus ? <>
      <li><CustomMenu1 {...menuProps1} /></li>
      <li><CustomMenu2 {...menuProps2} /></li>
      </> : <li className={styles.specLi}><Select
        showArrow={false}
        value={value1}
        allowClear={!value1.includes('打印')}
        loading={fetching}
        onDropdownVisibleChange={(bool)=> bool && handleGetFashion()}
        onChange={(val)=>val ? setSelected([val]) : handleCheck()}
        dropdownMatchSelectWidth={465}
        dropdownRender={(child) => (
          <div onMouseDown={e => { e.preventDefault(); e.stopPropagation();}}>
            {radioContent()}
            <div className={styles.fashionBox} id='hotGoodsSortBox'>
              {child}
            </div>
          </div>
        )}
      >
       {newRenderGoods()}
      </Select></li>
    }
  </CustomRadioBtn></div>)

  return (<div style={{display:"flex"}}>
    <Select value={showStatus} onChange={e => setShowStatus(e)} style={{ padding: '0px'}}>
      <Option value={0}>爆款商品-按商品</Option>
      <Option value={1}>爆款商品-按款</Option>
    </Select>
    {
      showStatus == 0 ? (<Select
        allowClear
        value={value1}
        placeholder={`您有${hotGoodsCount}件爆款商品待打印`}
        loading={fetching}
        onDropdownVisibleChange={(bool)=> bool && handleGetFashion()}
        onChange={(val)=>setSelected(val ? [val] : [])}
        dropdownMatchSelectWidth={465}
        dropdownRender={(child) => (
          <div onMouseDown={e => { e.preventDefault(); e.stopPropagation();}}>
            {radioContent()}
            <div className={styles.fashionBox} id='hotGoodsSortBox'>
              {child}
            </div>
          </div>
        )}
      >
       {newRenderGoods()}
      </Select>) : (<>
       <span><CustomMenu1 {...menuProps1} /></span>
       <span><CustomMenu2 {...menuProps2} /></span>
        {/* <Select
        style={{width:'200px'}}
        allowClear
        maxTagCount='responsive'
        mode="multiple"
        placeholder='选择商品'
        // value={selected?.length ? [`已选${selected?.length}`] : undefined}
        loading={fetching}
        onDropdownVisibleChange={onDropdownVisibleChange}
        onChange={(val)=>setSelected(val)}
        dropdownMatchSelectWidth={465}
        dropdownRender={(child) => (
          <div onMouseDown={e => { e.preventDefault(); e.stopPropagation();}}>
          {radioContent()}
          <div className={styles.fashionBox} id='hotGoodsSortBox'>
            {child}
          </div>
          </div>
        )}
      >
       {newRenderGoods()}
      </Select> */}
        {/* <Select
          placeholder='颜色规格'
          dropdownMatchSelectWidth={465}
          value={selected2?.length ? `已选${selected2?.length}` : null}
          onDropdownVisibleChange={(bool)=>console.log(bool)}
          dropdownRender={() => (
            <div onMouseDown={e => { e.preventDefault(); e.stopPropagation();}}>
             {radioContent()}
            </div>
          )}
        /> */}
      </>)
    }
  </div>)
}